package com.ming.springboot.data;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by mqsi on 2022/5/15 18:38
 */
@RestControllerAdvice(basePackages = "com.ming.springboot.controller")
@Slf4j
public class GlobalExceptionHandler {

	// 系统异常处理
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(Throwable.class)
	public ErrorResult handleThrowable(Throwable e, HttpServletRequest request){
		ErrorResult errorResult = ErrorResult.fail(ResultCode.SYSTEM_ERROR, e);
		log.error("URL:{}, 系统异常：{}", request.getRequestURI(), e);
		return errorResult;
	}

	// 自定义异常处理
	@ExceptionHandler(BusinessException.class)
	public ErrorResult handleBusinessException(BusinessException e, HttpServletRequest request){
		ErrorResult error = ErrorResult.builder().resultCode(e.getCode())
				.message(e.getMessage())
				.exception(e.getClass().getName()).build();
		log.warn("URL:{}, 业务异常：{}", request.getRequestURI(), error);
		return error;
	}
}
